<template>
  <div class="employee-add-container">
    <div class="description-section">
      <h2>五、员工添加</h2>
      <div class="description-content">
        <div class="desc-item">
          <strong>功能描述：</strong>
          <p>实现医院员工账号的批量创建与信息维护，包括医生、护士、行政人员等角色，支持导入 Excel 模板快速初始化数据。</p>
        </div>
        <div class="desc-item">
          <strong>操作流程：</strong>
          <p>选择员工类型，填写姓名、工号、所属科室等信息；如需批量导入，下载模板填写后上传，系统自动校验并创建账号。</p>
        </div>
      </div>
    </div>

    <el-card class="card">
      <template #header>
        <div class="card-header">
          <span>员工添加</span>
        </div>
      </template>

      <div class="layout">
        <el-form ref="formRef" :model="form" :rules="rules" label-width="100px" class="employee-form">
          <el-row :gutter="16">
            <el-col :span="12">
              <el-form-item label="用户名" prop="userName">
                <el-input v-model="form.userName" placeholder="登录用户名" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="真实姓名" prop="fullName">
                <el-input v-model="form.fullName" placeholder="员工姓名" />
              </el-form-item>
            </el-col>

            <el-col :span="12">
              <el-form-item label="工号" prop="employeeNo">
                <el-input v-model="form.employeeNo" placeholder="唯一工号" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="所属科室" prop="departmentId">
                <el-select v-model="form.departmentId" placeholder="请选择科室">
                  <el-option v-for="d in departments" :key="d.id" :label="d.name" :value="d.id" />
                </el-select>
              </el-form-item>
            </el-col>

            <el-col :span="12">
              <el-form-item label="手机" prop="phone">
                <el-input v-model="form.phone" placeholder="手机号" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="邮箱" prop="email">
                <el-input v-model="form.email" placeholder="邮箱地址" />
              </el-form-item>
            </el-col>

            <el-col :span="12">
              <el-form-item label="性别" prop="gender">
                <el-radio-group v-model="form.gender">
                  <el-radio label="M">男</el-radio>
                  <el-radio label="F">女</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="地址" prop="address">
                <el-input v-model="form.address" placeholder="联系地址" />
              </el-form-item>
            </el-col>

            <el-col :span="12">
              <el-form-item label="联系人" prop="emergencyContact">
                <el-input v-model="form.emergencyContact" placeholder="紧急联系人" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="身份证" prop="idNumber">
                <el-input v-model="form.idNumber" placeholder="身份证号码" />
              </el-form-item>
            </el-col>

            <el-col :span="12">
              <el-form-item label="职务" prop="position">
                <el-input v-model="form.position" placeholder="岗位/职务" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="职称" prop="title">
                <el-input v-model="form.title" placeholder="如 主治医师" />
              </el-form-item>
            </el-col>
          </el-row>

          <div class="btn-row">
            <el-button type="primary" @click="onSubmit">提交</el-button>
            <el-button @click="onReset">重置</el-button>
          </div>
        </el-form>

        <div class="import-panel">
          <div class="panel-title">批量导入</div>
          <div class="import-actions">
            <el-button @click="downloadTemplate">下载模板</el-button>
            <el-upload :show-file-list="false" :http-request="handleUpload">
              <el-button type="success">导入Excel</el-button>
            </el-upload>
          </div>
          <p class="tips">支持 xlsx/xls；建议先下载模板填写再上传。</p>
        </div>
      </div>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { reactive, ref } from 'vue'
import { ElMessage, type FormInstance } from 'element-plus'
import { writeApi } from '@/api/http'

const formRef = ref<FormInstance>()

const form = reactive({
  userName: '',
  fullName: '',
  employeeNo: '',
  departmentId: undefined as number | undefined,
  phone: '',
  email: '',
  gender: 'M',
  address: '',
  emergencyContact: '',
  idNumber: '',
  position: '',
  title: '',
})

const rules = {
  userName: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
  fullName: [{ required: true, message: '请输入真实姓名', trigger: 'blur' }],
  employeeNo: [{ required: true, message: '请输入工号', trigger: 'blur' }],
  departmentId: [{ required: true, message: '请选择科室', trigger: 'change' }],
}

// 科室下拉（可改为接口查询）
const departments = ref([
  { id: 1, name: '内科' },
  { id: 2, name: '外科' },
  { id: 3, name: '儿科' },
])

const onSubmit = () => {
  formRef.value?.validate(async (valid) => {
    if (!valid) return
    try {
      const payload = { ...form }
      await writeApi.post('/Employee/Create', payload)
      ElMessage.success('提交成功')
      onReset()
    } catch (e) {
      ElMessage.error('提交失败')
    }
  })
}

const onReset = () => {
  formRef.value?.resetFields()
}

const downloadTemplate = () => {
  // 这里直接构造一个简单模板并下载；也可替换为后端下载链接
  const headers = ['userName', 'fullName', 'employeeNo', 'departmentId', 'phone', 'email', 'gender']
  const csv = headers.join(',') + '\n'
  const blob = new Blob([csv], { type: 'text/csv;charset=utf-8;' })
  const url = URL.createObjectURL(blob)
  const a = document.createElement('a')
  a.href = url
  a.download = '员工导入模板.csv'
  a.click()
  URL.revokeObjectURL(url)
}

const handleUpload = async (req: any) => {
  try {
    const fd = new FormData()
    fd.append('file', req.file as File)
    await writeApi.post('/Employee/Import', fd, { headers: { 'Content-Type': 'multipart/form-data' } })
    ElMessage.success('导入成功')
  } catch (e) {
    ElMessage.error('导入失败')
  }
}
</script>

<style scoped lang="scss">
.employee-add-container {
  padding: 20px;
  background-color: #f5f5f5;
  min-height: 100vh;
}

.description-section {
  margin-bottom: 20px;
  background: white;
  padding: 20px;
  border-radius: 4px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);

  h2 { margin: 0 0 15px 0; font-size: 18px; color: #333; }
}

.card { }

.layout {
  display: grid;
  grid-template-columns: 2fr 1fr;
  gap: 20px;
}

.btn-row { display: flex; gap: 10px; }

.import-panel {
  border: 1px solid #e4e7ed;
  border-radius: 4px;
  background: #fff;
  padding: 16px;

  .panel-title { font-weight: 600; margin-bottom: 12px; }
  .import-actions { display: flex; gap: 10px; margin-bottom: 8px; }
  .tips { color: #909399; font-size: 12px; }
}
</style>


